<template>
  <div>
    <div class="crud-group">
      <el-input
        v-model="paramsForm.taskName"
        placeholder="请输入任务名称"
        type="text"
        clearable
      />
      <el-input
        v-model="paramsForm.sourceName"
        placeholder="请输入同步方式"
        type="text"
        clearable
      />
      <el-input
        v-model="paramsForm.libraryTableName"
        placeholder="请输入表名称"
        type="text"
        clearable
      />
      <el-select
        v-model="paramsForm.taskState"
        placeholder="请选择状态"
        clearable
      >
        <el-option
          label="进行中"
          value="进行中"
        />
        <el-option
          label="已完成"
          value="已完成"
        />
        <el-option
          label="失败"
          value="失败"
        />
      </el-select>
      <div>
        <el-button
          type="success"
          icon="el-icon-search"
          @click="getData"
        > 搜索 </el-button>
        <el-button
          type="warning"
          icon="el-icon-refresh-left"
          @click="reset"
        > 重置 </el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addopen"
        >新增</el-button>
      </div>
    </div>

    <el-table
      v-loading="isLoading"
      :data="data"
      border
    >
      <el-table-column
        label="任务名称"
        prop="taskName"
        min-width="100px"
      />
      <el-table-column
        label="同步方式"
        prop="sourceName"
        min-width="250px"
      />
      <el-table-column
        label="表名称"
        prop="libraryTableName"
        min-width="100px"
      >
        <template slot-scope="scope">
          <a
            v-if="scope.row.libraryTableName"
            style="color: dodgerblue"
            @click="() => {
              libraryTableName = '';
              libraryTableName = scope.row.libraryTableName;
              libraryTableNameFlag = true;
            }
            "
          >查看表名称</a>
          <span
            v-else
            style="color: dodgerblue"
          >全量</span>
        </template>
      </el-table-column>
      <el-table-column
        label="hdfs数量"
        prop="tableHdfsNumber"
        width="130px"
      />
      <el-table-column
        label="热备用时"
        prop="standbyTime"
        min-width="80px"
      />
      <el-table-column
        label="状态"
        prop="taskState"
        width="80px"
      >
        <template slot-scope="scope">
          <el-tag :type="getStateColor(scope.row.taskState)">
            {{ scope.row.taskState }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        prop="createTime"
        width="140px"
      />
      <el-table-column
        label="表信息"
        width="66px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="detailClick(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        :current-page="paramsForm.current"
        :page-size="paramsForm.size"
        :page-sizes="[5, 10, 20, 30, 40]"
        layout="prev, pager, next,sizes,total"
        :total="total"
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
      />
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :before-close="eCloses"
      :visible.sync="eFlag"
      append-to-body
      title="详情信息"
      width="1000px"
    >
      <div class="crud-group">
        <el-input
          v-model="dialogForm.libraryTableName"
          placeholder="请输入库表名"
          type="text"
          clearable
        />
        <el-select
          v-model="dialogForm.taskState"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            label="失败"
            value="失败"
          />
          <el-option
            label="已完成"
            value="已完成"
          />
        </el-select>
        <div>
          <el-button
            type="success"
            @click="dialogSearch"
          > 搜索 </el-button>
          <el-button
            type="warning"
            @click="dialogReset"
          > 重置 </el-button>
        </div>
      </div>

      <el-table
        v-loading="dialogLoading"
        :data="Tabledata"
        border
      >
        <el-table-column
          prop="taskName"
          label="所属任务名称"
          show-overflow-tooltip
          width="100px"
        />
        <el-table-column
          prop="libraryTableName"
          label="库表名"
          sortable
          show-overflow-tooltip
        />
        <el-table-column
          prop="standbyTime"
          label="同步用时"
          show-overflow-tooltip
          width="88px"
        />
        <el-table-column
          label="日志"
          show-overflow-tooltip
          width="80px"
        >
          <template slot-scope="scope">
            <a
              v-if="scope.row.log"
              style="color: dodgerblue"
              @click="() => {
                errorLog = '';
                errorLog = scope.row.log;
                errorlogVisible = true;
              }
              "
            >查看日志</a>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          prop="taskState"
          width="88px"
        >
          <template slot-scope="scope">
            <el-tag :type="getStateColor(scope.row.taskState)">
              {{ scope.row.taskState }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
          width="140px"
        />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          :current-page="dialogForm.current"
          :page-size="dialogForm.size"
          :page-sizes="[5, 10, 20, 30, 40]"
          layout="prev, pager, next,sizes,total"
          :total="dialogForm.total"
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
        />
      </div>
    </el-dialog>

    <el-dialog
      width="50%"
      title="日志详情"
      :visible="errorlogVisible"
      append-to-body
      @close="errorclose"
    >
      <codemirror
        :value="errorLog"
        class="code"
        :read-only="true"
      />
      <span
        slot="footer"
        class="dialog-footer"
        style="text-align: center"
      >
        <el-button
          type="primary"
          @click="errorclose"
        >关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      width="30%"
      title="表名称详情"
      :visible="libraryTableNameFlag"
      append-to-body
      @close="libraryTableclose"
    >
      <div>
        <codemirror
          ref="codemirror"
          :value="libraryTableName"
          :editor-height="200"
          :read-only="true"
        />
      </div>
      <span
        slot="footer"
        class="dialog-footer"
        style="text-align: center"
      >
        <el-button
          type="primary"
          @click="libraryTableclose"
        >关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog
      width="35rem"
      title="新增"
      :visible.sync="addVisible"
      append-to-body
      @close="addclose"
    >
      <el-form
        ref="addForm"
        :inline="true"
        label-width="120px"
        :model="addForm"
      >
        <el-form-item
          label="选择"
        >
          <el-radio-group
            v-model="addForm.mode"
            @input="(val)=>{
              this.$refs['addForm'].clearValidate();
              if(val === '表级'){
                addForm.tableName = ''
              }
              else if(val === '库级'){
                addForm.dbName = ''
              }else{
                addForm.dbName = ''
                addForm.tableName = ''
              }
            }
            "
          >
            <el-radio label="源库表级" />
            <el-radio label="库级" />
            <el-radio label="表级" />
          </el-radio-group>
        </el-form-item>

        <div v-if="addForm.mode === '源库表级'">
          <el-form-item
            label="数据源"
            prop="source"
            :rules="
              [
                { required: true, message: '请输入源名称', trigger: 'blur' },
              ]
            "
          >
            <el-select
              v-model="addForm.source"
              placeholder="请选择数据源"
              filterable
              :disabled="loading"
              clearable
              @change="changesoure"
            >
              <el-option
                v-for="val in sourceList"
                :key="val"
                v-loading="addForm.sourceListLoading"
                :label="val"
                :value="val"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="数据库"
            prop="dbName"
          >
            <el-select
              v-model="addForm.dbName"
              placeholder="请选择数据库"
              filterable
              :disabled="loading"
              clearable
              @change="changetblDatabaseName"
            >
              <el-option
                v-for="val in tblDatabaseNameList"
                :key="val"
                v-loading="addForm.tblDatabaseNameListLoading"
                :label="val"
                :value="val"
              />
            </el-select>

          </el-form-item>

          <el-form-item
            label="数据表"
            prop="tableName"
          >
            <el-select
              v-model="addForm.tableName"
              placeholder="请选择数据表"
              filterable
              :disabled="loading"
              clearable
            >
              <el-option
                v-for="val in tableNameList"
                :key="val"
                v-loading="addForm.tableNameListListLoading"
                :label="val"
                :value="val"
              />
            </el-select>

          </el-form-item>

        </div>

        <div
          v-else-if="addForm.mode === '库级'"
        >
          <el-form-item
            label="数据库"
            prop="dbName"
            :rules="
              [
                {
                  required: true, message: '请输入库名', trigger: 'blur'
                }
              ]
            "
          >
            <el-input
              v-model="addForm.dbName"
              placeholder="请输入数据库"
            />
          </el-form-item>

          <el-form-item
            label="黑名单"
            prop="blackList"
          >
            <el-select
              v-model="addForm.blackList"
              clearable
              multiple
              collapse-tags
              placeholder="请选择"
            >
              <!-- eslint-disable-next-line vue/valid-v-for -->
              <el-option
                v-for="item in blackListOptions"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div
          v-else-if="addForm.mode === '表级'"
        >
          <el-form-item
            label="数据表"
            prop="tableName"
            :rules="
              [
                {
                  required: true, message: '请输入格式：库名.表名', trigger: 'blur',pattern:/^\w+\.\w+$/g
                }
              ],
            "
          >
            <el-input
              v-model="addForm.tableName"
              placeholder="请输入数据表"
            />

          </el-form-item>

          <el-form-item
            label="同步方式"
            prop="quantity"
          >
            <el-radio-group v-model="addForm.quantity">
              <el-radio label="增量" />
              <el-radio label="全量" />
            </el-radio-group>
          </el-form-item>

        </div>

        <el-form-item
          v-if="!(addForm.mode === '表级' && addForm.quantity === '全量')"
          label="时间"
          prop="hotStandbyTime"
          :rules="
            [
              { required: true, message: '请选择日期', trigger: 'blur' }
            ]
          "
        >
          <el-date-picker
            v-model="addForm.hotStandbyTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy - MM - dd "
            value-format="yyyyMMdd"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          :disabled="loading"
          @click="addclose"
        >取消</el-button>
        <el-button
          type="primary"
          :disabled="loading"
          @click="addsubmit('addForm')"
        >提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import uatApi from '@/api/dashboard/uatSync'
import dateUtil from '@/utils/date'
import codemirror from '@/components/codemirror/codemirror.vue'

export default {
  components: {
    codemirror
  },
  data() {
    return {
      loading: false,
      data: [],
      isLoading: false,
      dialogLoading: false,
      paramsForm: {
        current: 1,
        size: 10,
        sourceName: '',
        taskState: '',
        standbyTime: '',
        libraryTableName: ''
      },
      total: 0,
      eFlag: false,
      detaildata: {},
      Tabledata: [],
      dialogForm: {
        current: 1,
        size: 10,
        total: 0,
        taskName: '',
        sourceName: '',
        libraryTableName: '',
        taskState: ''
      },
      addForm: {
        mode: '源库表级',
        source: '',
        dbName: '',
        tableName: '',
        quantity: '增量',
        blackList: [],
        cpWhether: '是',
        hotStandbyTime: [
          new Date(),
          new Date()
        ],
        sourceListLoading: false,
        tblDatabaseNameListLoading: false,
        tableNameListListLoading: false
      },
      dialogId: '',
      errorLog: '',
      errorlogVisible: false,
      addVisible: false,
      tableNameList: [],
      tblDatabaseNameList: [],
      sourceList: [],
      blackListOptions: [],
      libraryTableNameFlag: false,
      libraryTableName: ''
    }
  },
  mounted() {
    this.getData()
    // this.getaddlist();
  },
  methods: {
    async getData(resetPage = true) {
      if (resetPage) {
        this.paramsForm.current = 1
      }
      this.isLoading = true
      const param = this.paramsForm
      const res = await uatApi.getUATSyncLogs(param)
      this.data = res.records
      this.total = res.total
      this.isLoading = false
    },
    async getBlackList() {
      const params = {
        current: 1,
        size: 10000
      }
      const res = await uatApi.getUatBlackList(params)
      const blackOptions = []
      res.records.forEach((item) => {
        blackOptions.push({
          label: item.tblName,
          value: item.tblName
        })
      })
      this.blackListOptions = blackOptions
      this.addForm.blackList = res.records.map((item) => item.tblName)
    },
    reset() {
      this.paramsForm = {
        ...this.paramsForm,
        current: 1,
        sourceName: '',
        taskState: '',
        standbyTime: '',
        libraryTableName: ''
      }
      this.getData()
    },
    dialogReset() {
      this.dialogForm = {
        ...this.dialogForm,
        current: 1,
        total: 0,
        taskName: '',
        sourceName: '',
        libraryTableName: '',
        taskState: ''
      }
      this.getlogData(this.dialogId)
    },
    detailClick(row) {
      this.eFlag = true
      this.detaildata = row
      this.dialogId = row.id
      this.getlogData(row.id)
    },
    eCloses() {
      this.eFlag = false
    },
    getlogData(id, resetPage = true) {
      if (resetPage) {
        this.dialogForm.current = 1
      }
      this.dialogLoading = true
      var data = {
        current: this.dialogForm.current,
        size: this.dialogForm.size,
        taskId: id,
        sourceName: this.dialogForm.sourceName,
        libraryTableName: this.dialogForm.libraryTableName,
        taskState: this.dialogForm.taskState
      }
      uatApi
        .getalogs(data)
        .then((data) => {
          this.dialogLoading = false
          this.Tabledata = data.records
          this.dialogForm.total = data.total
        })
        .catch(() => {
          this.dialogLoading = false
        })
    },
    dialogSearch() {
      this.getlogData(this.dialogId)
    },
    errorclose() {
      this.errorlogVisible = false
    },
    // 分页
    handleSizeChange1(val) {
      this.paramsForm.current = 1
      this.paramsForm.size = val
      this.getData(false)
    },
    // 分页
    handleCurrentChange1(val) {
      this.paramsForm.current = val
      this.getData(false)
    },
    // 分页
    handleSizeChange2(val) {
      this.dialogForm.current = 1
      this.dialogForm.size = val
      this.getlogData(this.dialogId)
    },
    // 分页
    handleCurrentChange2(val) {
      this.dialogForm.current = val
      this.getlogData(this.dialogId, false)
    },
    getaddlist() {
      this.addForm.sourceListLoading = true
      var data = {
        source: this.addForm.source,
        dbName: this.addForm.dbName
      }
      uatApi
        .addlist(data)
        .then((data) => {
          this.sourceList = data.sourceName
          this.addForm.sourceListLoading = false
        })
        .catch(() => {
          this.dialogLoading = false
        })
    },
    addopen() {
      this.addVisible = true
      this.getaddlist()
      this.getBlackList()
    },
    addclose() {
      this.addVisible = false
      this.$refs['addForm'].resetFields()
      this.tblDatabaseNameList = []
      this.tableNameList = []
      this.addForm = {
        mode: '源库表级',
        source: '',
        dbName: '',
        tableName: '',
        blackList: [],
        cpWhether: '是',
        quantity: '增量',
        hotStandbyTime: [
          new Date(),
          new Date()
        ],
        sourceListLoading: false,
        tblDatabaseNameListLoading: false,
        tableNameListListLoading: false
      }
    },
    getDefaultData() {
      var date1 = new Date()
      var y = date1.getFullYear()
      var m = date1.getMonth() + 1
      var d = date1.getDate()
      var startTime = y + '' + '' + m + '' + d
      return startTime
    },
    addsubmit(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          var data = {
            level: this.addForm.mode,
            staDate: typeof this.addForm.hotStandbyTime[0] === 'string' ? parseInt(this.addForm.hotStandbyTime[0]) : dateUtil.getDateYMStr(this.addForm.hotStandbyTime[0]),
            endDate: typeof this.addForm.hotStandbyTime[1] === 'string' ? parseInt(this.addForm.hotStandbyTime[1]) : dateUtil.getDateYMStr(this.addForm.hotStandbyTime[1]),
            cpWhether: this.addForm.cpWhether
          }
          if (this.addForm.mode === '源库表级') {
            data.source = this.addForm.source
            data.dbName = this.addForm.dbName
            data.tableName = this.addForm.tableName
          } else if (this.addForm.mode === '库级') {
            data.dbName = this.addForm.dbName
            data.uatBlackListList = this.addForm.blackList
          } else if (this.addForm.mode === '表级') {
            data.tableName = this.addForm.tableName
            data.quantity = this.addForm.quantity
            if (this.addForm.quantity === '全量') {
              delete data.staDate
              delete data.endDate
            }
          }

          if (this.addForm.mode === '源库表级') {
            uatApi
              .addsubmit(data)
              .then(() => {
                this.getData()
              })
          } else {
            uatApi
              .addSubmitLibTable(data)
              .then((res) => {
                if (res.error && res.error === '当前库下暂无表信息') {
                  this.$notify({
                    title: '提示',
                    message: '当前库下暂无表信息',
                    type: 'error'
                  })
                  return
                }
                this.getData()
              })
          }

          this.addVisible = false
          this.isLoading = true
          await new Promise((resolve) => {
            setTimeout(() => {
              resolve()
            }, 1500)
          })
          this.getData()
        } else {
          return false
        }
      })
    },
    changesoure() {
      this.loading = true
      this.addForm.tblDatabaseNameListLoading = true
      this.addForm.dbName = ''
      this.addForm.tableName = ''
      var data = {
        source: this.addForm.source,
        dbName: this.addForm.dbName
      }
      uatApi
        .addlist(data)
        .then((data) => {
          this.tblDatabaseNameList = data.tblDatabaseNameList
          this.addForm.tblDatabaseNameListLoading = false
          this.loading = false
        })
        .catch(() => { })
    },
    changetblDatabaseName() {
      this.loading = true
      this.addForm.tableNameListListLoading = true
      this.addForm.tableNameList = ''
      this.addForm.tableName = ''
      var data = {
        source: this.addForm.source,
        dbName: this.addForm.dbName
      }
      uatApi
        .addlist(data)
        .then((data) => {
          this.tableNameList = data.tblNameList
          this.addForm.tableNameListListLoading = false
          this.loading = false
        })
        .catch(() => { })
    },
    libraryTableclose() {
      this.libraryTableNameFlag = false
    },
    getStateColor(state) {
      switch (state) {
        case '进行中':
          return ''
        case '已完成':
          return 'success'
        default :
          return 'danger'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
